import os
import glob
import cv2
import numpy as np
from PIL import Image

reversal = True
sli = 300
start_index = 0
result_path = "test/library/"
base_name = "library-"
extension = ".jpg"
# 获取文件夹下已存在的文件名列表
existing_files = [filename for filename in os.listdir(result_path) if filename.startswith(base_name)]
# 计算新的文件名
result_name = base_name + str(len(existing_files) + 1) + extension

# 放置原始图片的路径
# base = 'G:\\MyFile\\sky\\630\\IMG_20230630_031857\\'
base = 'D:\\picture\\library\\'
# base = 'G:\\MyFile\\sky\\721Lr\\'
names = sorted(os.listdir(base))
frame = None
if sli is not None:
    amount = sli
else:
    amount = len(glob.glob(os.path.join(base, '*.jpg')))

for count, name in enumerate(names):
    if count < start_index:
        continue
    elif count > (sli + start_index):
        break
    else:
        if os.path.splitext(name)[1].lower() == '.jpg':
            percentage = count / amount * 100
            print(f'{percentage:.2f}%')
            path = os.path.join(base, name)
            curr = cv2.imread(path)
            if reversal:
                alpha = (count + 1) / amount
                if frame is None:
                    frame = curr * alpha
                else:
                    curr = curr * alpha
                    frame = np.maximum(frame, curr)
            else:
                if frame is None:
                    frame = curr
                else:
                    alpha = count / amount
                    print(alpha)
                    curr = curr * (1 - alpha)
                    frame = np.maximum(frame, curr)

# image_paths = []
# # 初始化叠加结果
# result = None
# im = None
#
# # for i in range(72, 120):
# #     filename = f'img/A{i:04d}.jpg'
# #     # img = cv2.imread(filename)
# #     image_paths.insert(0, filename)
#
# # 叠加处理
# for image_path in image_paths:
#     curr = cv2.imread(image_path)
#     if im is None:
#         im = curr
#     else:
#         im = np.maximum(im, curr)

# 调整亮度和对比度
# canvas = np.clip((frame * 1.1 + 10), 0, 255).astype(np.uint8)

# 显示结果
# cv2.namedWindow("startrails", 0)
# cv2.resizeWindow("startrails", 1200, 900)
# cv2.imshow("startrails", frame)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
cv2.imwrite("test/library/" + result_name, frame)
